import { getTextFromNodeOrFrag } from '../get';
import { record } from '../revoke/record';

let root;
let selection, range;

function setRoot(a){
  if(typeof a === 'string') root = document.querySelector(a);
  else if(a instanceof Node) root = a;
  else {
    console.error(`copy handler set root: root-${root} is not a string or node`);
  }
}

function copyHandler(event) {
  event.preventDefault();

  record();

  selection = window.getSelection();
  if(!selection.rangeCount) return;
  range = selection.getRangeAt(0);

  let frag = range.cloneContents();

  let res = getTextFromNodeOrFrag(frag);

  event.clipboardData.setData('text/plain', res);
}

export {
  setRoot, 
  copyHandler
}